/* -*- coding: utf-8 -*-

 Peerscape Firefox extension: components/peerscapeproxy.js

 Copyright 2008 Helsinki Institute for Information Technology
 and the authors.

 Authors:
       Konrad Markus <konrad.markus@hiit.fi>


 Permission is hereby granted, free of charge, to any person
 obtaining a copy of this software and associated documentation files
 (the "Software"), to deal in the Software without restriction,
 including without limitation the rights to use, copy, modify, merge,
 publish, distribute, sublicense, and/or sell copies of the Software,
 and to permit persons to whom the Software is furnished to do so,
 subject to the following conditions:

 The above copyright notice and this permission notice shall be
 included in all copies or substantial portions of the Software.

 THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
 CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
 TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
 SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/


/***********************************************************
 constants
***********************************************************/
// reference to the interface
const nsIPeerscapeProxy = Components.interfaces.nsIPeerscapeProxy;

// reference to the required base interface that all components must support
const nsISupports = Components.interfaces.nsISupports;

// UUID uniquely identifying our component
// You can get from: http://kruithof.xs4all.nl/uuid/uuidgen here
const CLASS_ID = Components.ID("{fb26ed20-c5f3-11dd-ad8b-0800200c9a66}");

// description
const CLASS_NAME = "Peerscape Proxy Component";

// textual unique identifier
const CONTRACT_ID = "@p2p-fusion.org/peerscape-proxy;1";

/***********************************************************
 class definition
***********************************************************/
// constructor
function PeerscapeProxy() {
    this.wrappedJSObject = this;
    this.init();
}

// definition
PeerscapeProxy.prototype = {
    QueryInterface: function(aIID) {
        if (!aIID.equals(nsIPeerscapeProxy) &&    
            !aIID.equals(nsISupports)) {
            throw Components.results.NS_ERROR_NO_INTERFACE;
        }
        return this;
    },

    PSRE: /hexlabel.net$/,
    homeURI: 'http://my.hexlabel.net/',
    proxy: null,

    prefService: Components.classes["@mozilla.org/preferences-service;1"].getService(Components.interfaces.nsIPrefBranch),
    proxyService: Components.classes["@mozilla.org/network/protocol-proxy-service;1"].getService(Components.interfaces.nsIProtocolProxyService),

    init: function() {
        this.checkPrefs();
        this.updateFilter();
    },
    exit: function() {
        this.proxyService.unregisterFilter(this);
    },

    /*  This function performs the filtering.
        Must return a nsIProxyInfo instance if it wants to apply the proxy 
    */
    applyFilter: function(proxyService, URI, curProxy) {
        if (this.isOn()) {
            if (this.PSRE.test(URI.host)) {
                //debug('*HITF*: ' + URI.host);
                var host = this.getHost();
                var port = this.getPort();
                if (host == "localhost") {
                    // Just use IPv4 instead of looking up localhost.
                    host = "127.0.0.1";
                }
                return this.proxyService.newProxyInfo("http", host, port, 0, 0, null);
            }
        }
        return curProxy;
    },

    getHost: function() {
        return this.prefService.getCharPref('peerscape.host');
    },
    setHost: function(newHost) {
        this.prefService.setCharPref('peerscape.host', newHost);
    },

    getPort: function(newPort) {
        return this.prefService.getIntPref('peerscape.port');
    },
    setPort: function(newPort) {
        this.prefService.setIntPref('peerscape.port', newPort);
    },
    
    isOn: function() {
        return this.prefService.getBoolPref('peerscape.on');
    },
    setOn: function(bOn) {
        this.prefService.setBoolPref('peerscape.on', bOn);
        this.updateFilter();
    },

    updateFilter: function() {
        if (this.isOn()) {
            // register the proxy filter
            this.proxyService.unregisterFilter(this);
            this.proxyService.registerFilter(this, 0);
        }
        else {
            // unregister the proxy filter
            this.proxyService.unregisterFilter(this);
        }
    },

    checkPrefs: function() {
        try {
            this.getHost();
            this.getPort();
            this.isOn();
        }
        catch (ex) {
            // first time this is installed it will switch the proxy on
            this.setHost('localhost');
            this.setPort(35880);
            this.setOn(true);
        }
    }
}


/***********************************************************
 class factory

 This object is a member of the global-scope Components.classes.
 It is keyed off of the contract ID.
***********************************************************/
var PeerscapeProxyFactory = {
    createInstance: function (aOuter, aIID) {
        if (aOuter != null) {
            throw Components.results.NS_ERROR_NO_AGGREGATION;
        }
        return (new PeerscapeProxy()).QueryInterface(aIID);
    }
}

/***********************************************************
 module definition (xpcom registration)
***********************************************************/
var PeerscapeProxyModule = {
    registerSelf: function(aCompMgr, aFileSpec, aLocation, aType) {
        aCompMgr = aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
        aCompMgr.registerFactoryLocation(CLASS_ID, CLASS_NAME, CONTRACT_ID, aFileSpec, aLocation, aType);
    },

    unregisterSelf: function(aCompMgr, aLocation, aType) {
        aCompMgr = aCompMgr.QueryInterface(Components.interfaces.nsIComponentRegistrar);
        aCompMgr.unregisterFactoryLocation(CLASS_ID, aLocation);        
    },

    getClassObject: function(aCompMgr, aCID, aIID) {
        if (!aIID.equals(Components.interfaces.nsIFactory)) {
            throw Components.results.NS_ERROR_NOT_IMPLEMENTED;
        }
        if (aCID.equals(CLASS_ID)) {
            return PeerscapeProxyFactory;
        }
        throw Components.results.NS_ERROR_NO_INTERFACE;
    },

    canUnload: function(aCompMgr) { return true; }
}

/***********************************************************
 module initialization

 When the application registers the component, this function
 is called.
***********************************************************/
function NSGetModule(aCompMgr, aFileSpec) { return PeerscapeProxyModule; }

